package com.leoman.spinningmachine.tab1;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.leoman.helper.util.FrescoUtil;
import com.leoman.helper.util.LogUtil;
import com.leoman.helper.util.ToastUtil;
import com.leoman.spinningmachine.R;
import com.leoman.spinningmachine.base.BaseActivity;
import com.leoman.spinningmachine.bean.LeaveTypeBean;
import com.leoman.spinningmachine.constant.Constant;
import com.leoman.spinningmachine.http.APIResponse;
import com.leoman.spinningmachine.http.WebServiceApi;
import com.leoman.spinningmachine.login.LoginActivity;
import com.leoman.spinningmachine.util.DateUtil;
import com.leoman.spinningmachine.util.DialogUtils;
import com.leoman.spinningmachine.util.SharedPreferencesUtils;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.leoman.spinningmachine.constant.Urls.HEAD_IMAGE;

/**
 * Created by Administrator on 2018-05-17.
 * 请假审批 新增
 */

public class AskLeaveActivity extends BaseActivity implements OnDateSetListener {

    @BindView(R.id.rl_leave_type)
    RelativeLayout rl_leave_type;
    @BindView(R.id.tv_leave_type)
    TextView tv_leave_type;
    @BindView(R.id.rl_leave_startTime)
    RelativeLayout rl_leave_startTime;
    @BindView(R.id.tv_leave_startTime)
    TextView tv_leave_startTime;
    @BindView(R.id.iv_pic)
    SimpleDraweeView iv_pic;
    @BindView(R.id.tv_spman_name)
    TextView tv_spman_name;
    @BindView(R.id.rl_leave_endTime)
    RelativeLayout rl_leave_endTime;
    @BindView(R.id.tv_leave_endTime)
    TextView tv_leave_endTime;
    @BindView(R.id.et_leave_day)
    TextView etLeaveDay;
    @BindView(R.id.et_leave_reason)
    EditText et_leave_reason;
    @BindView(R.id.btn_submit)
    TextView btn_submit;
    @BindView(R.id.rb_other)
    CheckBox rb_other;
    @BindView(R.id.rl_jobId)
    RelativeLayout rl_jobId;
    @BindView(R.id.ed_jobId)
    EditText ed_jobId;

    private String selType = ""; //选择的请假类型
    private String selStartTime = ""; //选择的开始时间
    private String selEndTime = ""; //选择的结束时间
    private int timeIndex = -1; //1 开始时间  2 结束时间
    private TimePickerDialog mDialogAll;
    private long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L; // 十年的数据
    private String reason; //请假事由
    private String workNum; //输入工号
    private Dialog alertDialog;
    private List<LeaveTypeBean> leaveLists;
    private List<String> loopViewTypelists = new ArrayList<>();

    private int loopViewSelIndex = 0;
    private long selStartL;
    private long selEndL;
    private double leaveDay;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.ac_ask_leave;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initTitle("请假审批");

        FrescoUtil.setImg(this, iv_pic, HEAD_IMAGE + SharedPreferencesUtils.getInstance().getString(Constant.USER_MANAGERIMAGE));
        tv_spman_name.setText(SharedPreferencesUtils.getInstance().getString(Constant.USER_REALNAME));

        rb_other.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                rl_jobId.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    protected void initData() {
        WebServiceApi.getInstance().leaveType("", this, 1);
    }

    @OnClick({R.id.rl_leave_type, R.id.rl_leave_startTime, R.id.rl_leave_endTime, R.id.btn_submit})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_leave_type:
                showLeaveType();
                break;
            case R.id.rl_leave_startTime:
                showTimeDialog(1);
                break;
            case R.id.rl_leave_endTime:
                showTimeDialog(2);
                break;
            case R.id.btn_submit:
                submitData();
                break;
        }
    }

    private void showLeaveType() {
        alertDialog = new Dialog(this, R.style.MyDialogStyle);
        alertDialog.show();
        alertDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        alertDialog.getWindow().setGravity(Gravity.CENTER);
        alertDialog.getWindow().setWindowAnimations(R.style.bottomAnim);
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.getWindow().setContentView(R.layout.dialog_leave_type);

        alertDialog.show();
        LoopView loopViewType = (LoopView) alertDialog.findViewById(R.id.loopViewLeft);
        if (loopViewTypelists != null && loopViewTypelists.size() > 0) {
            loopViewType.setItems(loopViewTypelists);
        }
        loopViewType.setInitPosition(50);
        loopViewType.setNotLoop();
        loopViewType.setTextSize(16);

        loopViewType.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int i) {
                loopViewSelIndex = i;
            }
        });
        alertDialog.getWindow().findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        alertDialog.getWindow().findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selType = leaveLists.get(loopViewSelIndex).getStatus();
                switch (selType) {
                    case "1":
                        tv_leave_type.setText("出差");
                        break;
                    case "2":
                        tv_leave_type.setText("事假");
                        break;
                    case "3":
                        tv_leave_type.setText("调休");
                        break;
                    case "4":
                        tv_leave_type.setText("病假");
                        break;
                    case "5":
                        tv_leave_type.setText("产假");
                        break;
                    case "6":
                        tv_leave_type.setText("陪产假");
                        break;
                    case "7":
                        tv_leave_type.setText("婚假");
                        break;
                    case "8":
                        tv_leave_type.setText("丧假");
                        break;
                    case "9":
                        tv_leave_type.setText("其他");
                        break;
                }
                alertDialog.cancel();
            }
        });
    }

    private void submitData() {
        reason = et_leave_reason.getText().toString().trim();
        workNum = ed_jobId.getText().toString().trim();
        String token = SharedPreferencesUtils.getInstance().getString("token");
        if (TextUtils.isEmpty(selType)) {
            DialogUtils.getInstance().showResultDialog(this, "请选择请假类型");
        } else if (TextUtils.isEmpty(selStartTime)) {
            DialogUtils.getInstance().showResultDialog(this, "请选择开始时间");
        } else if (TextUtils.isEmpty(selEndTime)) {
            DialogUtils.getInstance().showResultDialog(this, "请选择结束时间");
        } else if (TextUtils.isEmpty(reason)) {
            DialogUtils.getInstance().showResultDialog(this, "请输入请假事由");
        } else {
            DialogUtils.getInstance().show(this);
            WebServiceApi.getInstance().leaveNew(token, selStartTime, selEndTime, "" + leaveDay, "" + leaveLists.get(loopViewSelIndex).getId(), workNum, reason, this, 2);
        }
    }

    private void showTimeDialog(int i) {
        timeIndex = i;
        mDialogAll = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("点")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(Color.parseColor("#11C3E1"))
                .setToolBarTextColor(Color.parseColor("#11C3E1"))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();
        mDialogAll.show(getSupportFragmentManager(), "all");
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerDialog, long l) {
        if (1 == timeIndex) {
            selStartL = l;
            if (selEndL != 0 && selStartL > selEndL) {
                DialogUtils.getInstance().showResultDialog(this, "开始时间不能晚于结束时间");
                return;
            }
            selStartTime = DateUtil.getyMdHms(l, "yyyy-MM-dd HH:mm");
            tv_leave_startTime.setText("" + selStartTime);

        } else if (2 == timeIndex) {
            selEndL = l;
            if (selStartL != 0 && selStartL > selEndL) {
                DialogUtils.getInstance().showResultDialog(this, "开始时间不能晚于结束时间");
                return;
            }
            selEndTime = DateUtil.getyMdHms(l, "yyyy-MM-dd HH:mm");
            tv_leave_endTime.setText("" + selEndTime);
        }
        if (selStartL != 0 && selEndL != 0) {
            double tmpleaveDay = (selEndL - selStartL) / (1000 * 60 * 60 * 24.0);
            leaveDay = (double) Math.round(tmpleaveDay * 10) / 10;
            LogUtil.json("tmpleaveDay:" + tmpleaveDay + ",leaveDay:" + leaveDay);
            etLeaveDay.setText("" + leaveDay);
        }
    }

    @Override
    public void OnSuccessData(APIResponse apiResponse, Integer tag) {
        DialogUtils.getInstance().cancel();
        if (2 == tag) {
            ToastUtil.showToast(this, apiResponse.message, Toast.LENGTH_SHORT);
            finish();
        } else if (1 == tag) {
            leaveLists = apiResponse.data.list;
            for (int i = 0; i < leaveLists.size(); i++) {
                String name = leaveLists.get(i).getName();
                String id = "" + leaveLists.get(i).getId();
                loopViewTypelists.add(name);
            }

        }
    }

    @Override
    public void OnFailureData(String error, Integer tag) {
        super.OnFailureData(error, tag);
        DialogUtils.getInstance().cancel();
    }

    @Override
    public void OnErrorData(String code, Integer tag) {
        super.OnErrorData(code, tag);
        DialogUtils.getInstance().cancel();
        if ("100".equals(code)) {
            SharedPreferencesUtils.getInstance().clear();
            ToastUtil.showToast(this, "登录已过期,请重新登录", Toast.LENGTH_SHORT);
            gotoOtherActivity(LoginActivity.class);
        }
    }

}